﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Interface;
using System.Configuration;
using Phoenix.ReflectionExtensions;
using PServiceBus.Core.Runtime;
using PServiceBus.Core.Logger;
using PServiceBus.Core.Runtime.Messages;
using PServiceBus.Core.Configuration;
using PServiceBus.Core.Runtime.Configuration;

namespace PServiceBus.Core.Manager {
    public class TopicMessageEnricherManager {
        static List<ITopicMessageEnricher> _enrichers;
        private static List<ITopicMessageEnricher> Enrichers {
            get {
                if (_enrichers == null) {
                    _enrichers = new List<ITopicMessageEnricher>();
                    foreach (var enricher in ConfigurationProvider.TopicEnricherConfigs) {
                        var ex = MethodHelper.Try(() =>
                        {
                            var msgEnricher = DynamicBroker.Broker[enricher.Type].New() as ITopicMessageEnricher;
                            _enrichers.Add(msgEnricher);
                        });
                        ESBLogger.Log(ex);
                    }
                }
                return _enrichers;
            }
        }


        /// <summary>
        /// Enrich the content of the message
        /// </summary>
        /// <param name="message"></param>
        public static void Enrich(ref TopicMessage message) {
            foreach (var enricher in Enrichers) enricher.Enrich(ref message);
        }
    }
}
